<?php

namespace app\api\controller;

use app\common\controller\Api;

use think\Db;
use app\admin\model\Enroll;




/**
 * 会员接口
 */
class Activity extends Api
{
    protected $noNeedLogin = 'getActivity,enroll';
    protected $noNeedRight = '*';

    /**
     * 获取活动
     */
    public function getActivity()
    {
        $this->checkParam(['type','id']);
        $id = $this->request->request('id');
        $type = $this->request->request('type');
        $ret = Db::name('activity')
            ->where('venue_id', $id)
            ->where('type', $type)
            ->where('deletetime',null)
            ->where('status','0')
            ->select()
            ->toArray();
        if ($ret) {
            foreach ($ret as &$v) {
                $v['num'] = Enroll::where('activity_id', $v['id'])->count();
                $isEnroll = Enroll::where('activity_id', $v['id'])->where('user_id', $this->auth->id)->find();
                if ($isEnroll) {
                    $v['isEnroll'] = true;
                } else{
                    $v['isEnroll'] = false;
                }
            }

        }
        $this->success('活动列表', $ret);
    }

    /*
     * 活动报名
     * */
    public function enroll()
    {
        $this->checkParam('id');
        $id = $this->request->request('id');
        $activity = Db::name('activity')->where('id', $id)->find();
        if (!$activity) {
            $this->error(__('暂无活动'));
        }

        if (strtotime($activity['etime']) > time()) {
            $this->error(__('活动已结束'));
        }
        $isEnroll = Enroll::where('activity_id', $id)->where('user_id', $this->auth->id)->find();
        if ($isEnroll) {
            $this->error(__('您已报名'));
        }
        $data = [
            'venue_id' => $activity['venue_id'],
            'activity_id' => $id,
            'user_id' => $this->auth->id,
            'time' => time()
        ];
        $ret = Enroll::insert($data);
        if ($ret) {
            $this->success('报名成功');
        } else {
            $this->error(__('报名失败请稍后再试'));
        }
    }
}
